package edu.egypt.filestream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

//objective 2: writing and reading a file
//objective 3: use DDMS to test the file creation
public class FileStreamSampleActivity extends Activity {

	private EditText editText;


	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        editText = (EditText)findViewById(R.id.editText1);
        
    }

	
	public void onButtonClick(View v) {
		
		if(v.getId() == R.id.buttonSave){
			try {
				FileOutputStream outputStream = openFileOutput("textfile.txt",MODE_WORLD_READABLE);
				OutputStreamWriter writer = new OutputStreamWriter(outputStream);
				writer.write(editText.getText().toString());
				writer.flush();
				writer.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}else if (v.getId() == R.id.buttonEmpty){
			editText.setText("");
		}else if (v.getId() == R.id.buttonLoad){
			
			try {
				FileInputStream inputStream = openFileInput("textfile.txt");
				InputStreamReader reader = new InputStreamReader(inputStream);
				char[] buffer = new char[100];
				StringBuffer s =new StringBuffer();
				
				int charRead;
				while((charRead = reader.read(buffer)) > 0){
					s.append(String.copyValueOf(buffer,0,charRead));
					buffer = new char[100];
				}
				
				editText.setText(s.toString());
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
}